﻿/********************************************************************************/
// <copyright file="CustomAuthorizeAttribute.cs" company="Asia E-Business Solutions">
//     Copyright © 2012. All right reserved
// </copyright>
// <history>
//     <change who="Phuoc Le" date="02/01/2013 10:11:58 AM">Created</change>
// </history>
/********************************************************************************/

using System;
using System.Web;
using System.Web.Mvc;
using JLL.China.Infrastructure.Services;
using System.Linq;

namespace JLL.China.Application
{
    /// <summary>
    /// http://schotime.net/blog/index.php/2009/02/17/custom-authorization-with-aspnet-mvc/
    /// </summary>
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        // the "new" must be used here because we are overriding
        // the Roles property on the underlying class
        public string Roles;

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");

            if (!httpContext.User.Identity.IsAuthenticated)
                return false;

            var sessionRole = httpContext.Session[Constants.Session_Role];
            if (sessionRole == null)
            {
                var acc = AdminService.GetAdmin(httpContext.User.Identity.Name);
                if (acc == null)
                {
                    return false;
                }
                else
                {
                    httpContext.Session[Constants.Session_Role] = acc.Role;
                    httpContext.Session[Constants.Session_User] = acc;
                    sessionRole = acc.Role;
                }
            }

            string[] roles = Roles.Split(',');

            if (roles.Length > 0 && !roles.Contains(sessionRole.ToString(), StringComparer.OrdinalIgnoreCase))
            {
                return false;
            }

            return true;
        }

        //protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        //{
        //    // Returns HTTP 530 - see comment in AdminUnauthorizedResult.cs.
        //    filterContext.Result = new AdminUnauthorizedResult();
        //}
    }

}
